package com.web_bloks.project.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.http.client.Request;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.RootPanel;
import com.web_bloks.project.pages.client.Base;
import com.web_bloks.storage.client.GearsOffline;
import com.web_bloks.system.client.Logger;
import com.web_bloks.url.client.Helper;
import com.web_bloks.url.client.UrlFields;
import com.web_bloks.user.client.User;
import com.web_bloks.user.client.UserManager;
import com.web_bloks.document.client.Namespace;
import com.web_bloks.document.client.Title;
import com.web_bloks.http.client.JSONCall;
import com.web_bloks.http.client.JSONCallback;
/**
 * 
 * @author Jean-Lou Dupont
 *
 * url scheme:
 * 1)  #page
 * 2)  #special:page
 *
 * History ==> [URL;QUERY]
 * URL     ==> [NAMESPACE:NAME]
 * 
 * Declare namespaces
 * 
 * 
 */

/* CONFIGURATION:
 * ==============
 * 
 *  page:             [page  ==> Title]
 *  TitleAccessList:  [Title ==> Conditions]
 *  ViewManager:      [Title ==> ContentPage]
 *  FlowManager:      [currentPage ==> nextPage], verifies entry conditions
 *  ContentPages:     [page_name   ==> ContentPage ]
 *  Namespaces:       ( Namespace list )
 */
/* DISPATCH:
 * =========
 *  history [ url, query ]
 *    => url => page => Title
 *      FLOW MANAGER:
 *      => Check Title conditions ( anon, user, admin)
 *      => Retrieve ContentPage for Title
 *        
 * 
 */
public class main implements EntryPoint, JSONCallback {

	//Gears related
	final static String MANAGED_LOCAL_STORE = "web_bloks";
	final static String MANIFEST_URL = "com.web_bloks.project.main.nocache.manifest";
	GearsOffline go = GWT.create(GearsOffline.class);
	
	// GUI related
	RootPanel rootPanel = null;
	
	public Base basePanel = null; // GWT.create(Base.class);

	// Application Managers etc.
	AppMessages			MSG 			= null;
	AppNamespaces		appNs			= null; 
	AppTitleAccessList	appAcl			= null;
	AppFlowManager		appFlowManager	= null;
	AppViewManager		appViewManager	= null;	
	AppConditionChecker	appCC			= null;
	AppUserMessageManager appUserMessage = null;
	AppPortalManager	appPortalManager= null;
	User				currentUser		= null; 
	/**
	 * Entry Point
	 */
	public void onModuleLoad() {

		//Window.alert(".onLoad");
		
		//setup gears offline mode
		go.setup(MANAGED_LOCAL_STORE, MANIFEST_URL);

		appNs			= GWT.create(AppNamespaces.class);

		Namespace.setNamespaces( appNs );
		Title.setNamespaces( appNs );
		
		MSG 			= GWT.create(AppMessages.class); 
		appAcl			= GWT.create(AppTitleAccessList.class);
		appFlowManager	= GWT.create(AppFlowManager.class);
		appViewManager	= GWT.create(AppViewManager.class);	
		appCC			= GWT.create(AppConditionChecker.class);
		appUserMessage	= GWT.create(AppUserMessageManager.class);
		appPortalManager= GWT.create(AppPortalManager.class);
		currentUser		= GWT.create(User.class); 

		// Initialization
		// ==============
		//initUser();
		basePanel = GWT.create(Base.class);
		setupUserParameters();		
		
		rootPanel = RootPanel.get();
		rootPanel.add(basePanel);
		
		//appViewManager ^^^
		
		appFlowManager.setViewManager( appViewManager );
		appFlowManager.setConditionChecker( appCC );
		appFlowManager.setTitleAccessList( appAcl );
		appFlowManager.setCurrentUser( currentUser );
		appFlowManager.doFinalInit();

		appPortalManager.setBasePage( basePanel );
		appPortalManager.setFlowManager( appFlowManager );
		appPortalManager.setUserMessageManager( appUserMessage );
		appPortalManager.setMessageManager( MSG );

		appCC.setCurrentUser(currentUser);
		
		appUserMessage.setMessageWidget( basePanel.getUserMessageWidget() );
		
		History.addHistoryListener( appPortalManager );

		UrlFields uf = Helper.extractFieldsFromLocation();
		if (null!=uf) {
			appPortalManager.navigateTo(uf);
		} else {
			appPortalManager.navigateToDefault();
		}
	}
	/* =====================================================================================================
 		INITIALIZATION
	===================================================================================================== */
	protected void setupUserParameters() {

		//UserManager
		UserManager um = GWT.create(UserManager.class);

		// init current user ... but we won't have the parameters
		// until the JSON call finishes
		currentUser = um.getCurrentUser();

		JSONCall jsc = GWT.create(JSONCall.class);
		jsc.setCallback(this);
		
		try {
			jsc.execute("/api/user//", null);
		} catch(Exception e) {
			Logger.logWarn(getClass()+".onModuleLoad: error performing /api/user/ call, msg="+e.getMessage());
		}
	}
	
	public void onJSONCallError(Request request, Throwable exception) {
		Logger.logWarn(getClass()+".onJSONCallError: error fetching from /api/user");
	}

	public void onJSONCallResponseReceived(int code, JSONValue response) {
		
		//UserManager
		UserManager um = GWT.create(UserManager.class);

		// init current user ... but we won't have the parameters
		// until the JSON call finishes
		currentUser = um.getCurrentUser();

		currentUser.initFromJSON( response );
		
		basePanel.setupTools();
		basePanel.doUpdate();
	}


}//END
